package io.renren.common.ueditor.upload;

import io.renren.common.ueditor.PathFormat;
import io.renren.common.ueditor.define.AppInfo;
import io.renren.common.ueditor.define.BaseState;
import io.renren.common.ueditor.define.FileType;
import io.renren.common.ueditor.define.State;
import io.renren.modules.app.constants.StringConstants;
import io.renren.modules.oss.cloud.OSSFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class BinaryUploader {

    public static final State save(HttpServletRequest request,
                                   Map<String, Object> conf) {

        if (!ServletFileUpload.isMultipartContent(request)) {
            return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
        }

        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());
            if (multipartFile == null) {
                return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
            }

            // 文件名处理
            String originFileName = multipartFile.getOriginalFilename();
            String suffix = FileType.getSuffixByFilename(originFileName);
            String prefix = originFileName.substring(0, originFileName.length() - suffix.length());
            long len = System.currentTimeMillis();

            // 路径处理
            String savePath = (String) conf.get("savePath") + File.separator;
            savePath = savePath + prefix + "_" + len + suffix;
            long maxSize = ((Long) conf.get("maxSize")).longValue();

            if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
                return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
            }
//			savePath = PathFormat.parse(savePath, originFileName);
            String physicalPath = (String) conf.get("rootPath") + savePath;

            // 判断文件上传本地还是OSS
            boolean uploadFlag = StringConstants.isOpenOss;
            if (uploadFlag) {
                BaseState bs = new BaseState();
                String url = OSSFactory.build().uploadSuffix(multipartFile.getBytes(), prefix + "_" + len + suffix);
                bs.putInfo("url", url);
                bs.putInfo("type", suffix);
                bs.putInfo("original", originFileName);
                return bs;
            } else {
                InputStream is = multipartFile.getInputStream();
                State storageState = StorageManager.saveFileByInputStream(is,
                        physicalPath, maxSize);
                is.close();
                if (storageState.isSuccess()) {
                    storageState.putInfo("url", PathFormat.format(File.separator + "static" + File.separator
                            + "file" + File.separator + savePath));
                    storageState.putInfo("type", suffix);
                    storageState.putInfo("original", originFileName);
                }
                return storageState;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseState(false, AppInfo.IO_ERROR);
    }

    private static boolean validType(String type, String[] allowTypes) {
        List<String> list = Arrays.asList(allowTypes);
        return list.contains(type);
    }

}
